<?php

namespace App\Console\Commands;

use App\Models\Account;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;

class GetClue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clue:all {--start=} {--end=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $today = Carbon::now()->toDateString();
        $date  = [
            'start' => $this->option('start') ?: $today,
            'end'   => $this->option('end') ?: $today,
        ];

        $validation = Validator::make($date, [
            'start' => 'date_format:Y-m-d',
            'end'   => 'date_format:Y-m-d',
        ]);

        if ($validation->fails()) {
            $this->error($validation->messages()->first());
        } else {
            $this->info("开始获取{$date['start']}到的{$date['end']}数据");
            $accounts = Account::where('enable', true)->get();
            $accounts->each(function ($account) use ($date) {
                $r    = $account->getClue($date['start'], $date['end'], true, true);

                if ($r['result']) {
                    $this->info("{ $account->name} 获取数据成功,一共获取了 {$r['count']}条");
                }
                else {
                    $this->warn("{$account->name}  获取失败");
                }
            });
        }
    }
}
